<?php

use app\model\Device;
use app\model\DeviceQualityInfo;
use Illuminate\Database\Capsule\Manager as Capsule;
use Workerman\Worker;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
use Webman\Event\Event;

require_once __DIR__ . '/vendor/autoload.php';

date_default_timezone_set('PRC');

$worker = new Worker();
$worker->onWorkerStart = function () {

    // 初始化数据库连接
    $capsule = new Capsule;

    $capsule->addConnection([
        'driver'      => 'mysql',
        'host'        => ini('DB_HOST'),
        'port'        => ini('DB_PORT'),
        'database'    => ini('DB_NAME'),
        'username'    => ini('DB_USER'),
        'password'    => ini('DB_PASSWORD'),
        'charset'     => 'utf8mb4',
        'collation'   => 'utf8mb4_general_ci',
        'prefix'      => 'wa_',
    ]);
    $capsule->setAsGlobal();
    $capsule->bootEloquent();
    $capsule->setEventDispatcher(new Dispatcher(new Container));

    $mqtt = new Workerman\Mqtt\Client(
        ini('MQTT_HOST') . ':' . ini('MQTT_PORT'),
        [
            'username' => ini('MQTT_USERNAME'),
            'password' => ini('MQTT_PASSWORD'),
        ],
    );
    $mqtt->onConnect = function ($mqtt) {
        $mqtt->subscribe('Topic_GO');
        $mqtt->subscribe('Topic_RETURN');
    };
    $mqtt->onMessage = function ($topic, $content) {
        var_dump($topic, $content);

        $data = json_decode($content, 1);

        // 中文字段到英文数据库字段映射
        $fields = [
            "进水压力" => "inlet_pressure",
            "进水流量" => "inlet_flow",
            "进水TDS" => "inlet_tds",
            "产水压力" => "outlet_pressure",
            "产水流量" => "outlet_flow",
            "产水余氯" => "outlet_chlorine",
            "产水温度" => "outlet_temp",
            "总进水量" => "total_inlet",
            "总产水量" => "total_outlet",
            "水箱液位" => "tank_level",
            "反洗时间" => "backwash_time",
            "反冲时间" => "backflush_time",
            "排空时间" => "drain_time",
            "正冲时间" => "forward_flush_time",
            "制水排放时间" => "water_production_drain_time",
            "过滤制水时间" => "filter_water_time",
            "浓水阀开度" => "concentrate_valve_opening",
            "水箱下限控制点" => "tank_lower_limit",
            "水箱上限控制点" => "tank_upper_limit",
            "手/自动状态" => "manual_auto_status",
            "自动状态" => "auto_status",
            "手动状态" => "manual_status",
            "4G信号IP" => "cellular_ip",
            "无线WIFI地址" => "wifi_address",
            "无线WIFI名" => "wifi_name",
            "有线IP地址" => "wired_ip_address",
            "漏水状态" => "leak_status",
            "水箱上限报警点" => "tank_upper_alarm",
            "水箱下限报警点" => "tank_lower_alarm",
            "TDS报警点" => "tds_alarm",
            "产水水温报警点" => "outlet_temp_alarm",
            "产水率报警基准" => "outlet_rate_alarm_base",
            "产水率报警偏差" => "outlet_rate_alarm_deviation"
        ];

        if ($topic == 'Topic_GO' && is_array($data) && ($data['GATEID'] ?? 0)) {

            $device = Device::query()->Where('gateway_id', $data['GATEID'])->first();

            if(empty($device)){
                var_dump('网关设备未找到');
                return;
            }

            // 构建英文字段数据
            $qualityData = [
                'device_id' => $device->id,
                'cl' => $data['CL'],
                'ph' => $data['PH'],
                'water' => $data['WATER'],
                'filter' => $data['FILTER'],
                'tds' => $data['TDS'],
                'status' => intval($data['STATUS']) ?? 0,
                'alarm' => intval($data['ALARM']) ?? 0,
                'auto' => intval($data['AUTO'] ?? 0) ?? 0,
            ];
            foreach ($fields as $cn => $en) {
                if (isset($data[$cn])) {
                    $value = $data[$cn];
                    // dump($value,is_float($value));
                    
                    // 如果是数字且不是空字符串，保留2位小数
                    if (is_float($value) && $value !== '') {
                        $value = round($value, 2);
                        // dump($value);
                    }
                    $qualityData[$en] = $value;
                }
            }

            // dump($qualityData);

            DeviceQualityInfo::query()->create($qualityData);

            $device = Device::updateOrCreate(
                [
                    'gateway_id' => $data['GATEID']
                ],
                [
                    'cl' => $data['CL'],
                    'ph' => $data['PH'],
                    'water' => $data['WATER'],
                    'filter' => $data['FILTER'],
                    'tds' => $data['TDS'],
                    'status' => intval($data['STATUS']) ?? 0,
                    'alarm' => intval($data['ALARM']) ?? 0,
                    'auto' => intval($data['AUTO'] ?? 0) ?? 0,
                    'last_send_at' => time(),
                    'is_online' => 1,
                ]
            );
        }
    };
    $mqtt->connect();
};
Worker::runAll();
